package com.example.guava;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * @author novel
 * @date 2020/10/30
 */
public class StringTest {
    public static void main(String[] args) {
        splitGuava();
    }

    private static void splitGuava() {
        String str = ",a ,,b ,";
        Iterable<String> split = Splitter.on(",")
                .omitEmptyStrings() // 忽略空值
                .trimResults() // 过滤结果中的空白
                .split(str);
        split.forEach(System.out::println);
        /*
         * a
         * b
         */
    }

    private static void splitJdk() {
        String str = ",a,,b,";
        String[] splitArr = str.split(",");
        Arrays.stream(splitArr).forEach(System.out::println);
        System.out.println("------");
        /*
         *
         * a
         *
         * b
         * ------
         */
    }

    private static void joinGuava() {
        ArrayList<String> list = Lists.newArrayList("a", "b", "c", null);
        String join = Joiner.on(",").skipNulls().join(list);
        System.out.println(join); // a,b,c

        String join1 = Joiner.on(",").useForNull("空值").join("旺财", "汤姆", "杰瑞", null);
        System.out.println(join1); // 旺财,汤姆,杰瑞,空值
    }

    private static void joinJdk() {
        // JDK 方式一
        ArrayList<String> list = Lists.newArrayList("a", "b", "c", null);
        String join = String.join(",", list);
        System.out.println(join); // a,b,c,null
        // JDK 方式二
        String result = list.stream().collect(Collectors.joining(","));
        System.out.println(result); // a,b,c,null
        // JDK 方式三
        StringJoiner stringJoiner = new StringJoiner(",");
        list.forEach(stringJoiner::add);
        System.out.println(stringJoiner.toString()); // a,b,c,null
    }
}
